package freighttmpl

import (
	"context"

	"mall/service/backend/api/internal/logic/setting/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/api/internal/utils"
	"mall/service/backend/api/internal/utils/parse"
	"mall/service/backend/common/i18n"
	"mall/service/setting/rpc/settingclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetFreightTemplateListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetFreightTemplateListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFreightTemplateListLogic {
	return &GetFreightTemplateListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetFreightTemplateListLogic) GetFreightTemplateList(req *types.FreightTemplateListReq) (resp *types.FreightTemplateListResp, err error) {
	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	var status uint32
	if req.Status != nil {
		status = *req.Status + 1
	}

	orderBys := util.ParseSorter(req.Sorter)
	filterBys := util.ParseFilter(req.Filter)
	data, err := l.svcCtx.SettingRpc.BackendGetFreightTemplateList(l.ctx, &settingclient.FreightTemplateListReq{
		Page:         page,
		PageSize:     pageSize,
		Name:         req.Name,
		FreeShipping: req.FreeShipping,
		ChargeMode:   req.ChargeMode,
		Status:       &status,
		OrderBy:      orderBys,
		FilterBy:     filterBys,
	})
	if err != nil {
		return nil, err
	}

	resp = &types.FreightTemplateListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.FreightTemplateListInfo{
			BaseListInfo: types.BaseListInfo{
				Current:  page,
				PageSize: pageSize,
				Total:    data.GetTotal(),
			},
		},
	}

	for _, v := range data.List {
		option := utils.GetOptionByStatus(v.Status)
		resp.Data.List = append(resp.Data.List, &types.FreightTemplateInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         v.Id,
				CreatedAt:  v.CreatedAt,
				UpdatedAt:  v.UpdatedAt,
				DeletedAt:  v.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Name:         v.Name,
			Remark:       v.Remark,
			FreeShipping: v.FreeShipping,
			ChargeMode:   v.ChargeMode,
			Sort:         v.Sort,
			Status:       v.Status,
		})
	}

	return resp, nil
}
